import 'package:flutter/material.dart';
import 'dart:math' as math;

/// 直升机旋翼式3D旋转组件
/// 
/// 模拟直升机旋翼的3D旋转效果：
/// 1. 图片在空间中倾斜摆放
/// 2. 围绕自身中心点进行旋转
/// 3. 旋转时图片的面不会移动，只是面本身在旋转
class HelicopterRotor3D extends StatefulWidget {
  /// 要旋转的子组件
  final Widget child;
  
  /// 旋转速度（每秒旋转圈数）
  /// 例如：0.1 = 每10秒旋转一圈，0.5 = 每2秒旋转一圈，1.0 = 每秒旋转一圈
  final double rotationSpeed;
  
  /// X轴倾斜角度（弧度）
  final double tiltAngleX;
  
  /// Y轴倾斜角度（弧度）
  final double tiltAngleY;
  
  /// 透视效果强度
  final double perspectiveValue;
  
  /// 是否启用自动旋转
  final bool enableAutoRotation;
  
  /// 是否启用透视效果
  final bool enablePerspective;
  
  /// 动画曲线
  final Curve animationCurve;
  
  /// 旋转角度变化回调
  final void Function(double angle)? onRotationChanged;

  const HelicopterRotor3D({
    Key? key,
    required this.child,
    this.rotationSpeed = 0.5, // 默认每2秒旋转一圈
    this.tiltAngleX = 0.3, // 默认X轴倾斜约17度
    this.tiltAngleY = 0.0,
    this.perspectiveValue = 0.001,
    this.enableAutoRotation = true,
    this.enablePerspective = true,
    this.animationCurve = Curves.linear,
    this.onRotationChanged,
  }) : super(key: key);

  @override
  State<HelicopterRotor3D> createState() => _HelicopterRotor3DState();
}

class _HelicopterRotor3DState extends State<HelicopterRotor3D>
    with TickerProviderStateMixin {
  late AnimationController _rotationController;
  late Animation<double> _rotationAnimation;

  @override
  void initState() {
    super.initState();
    
    _rotationController = AnimationController(
      duration: _calculateDuration(widget.rotationSpeed),
      vsync: this,
    );

    _rotationAnimation = Tween<double>(
      begin: 0.0,
      end: 2 * math.pi,
    ).animate(CurvedAnimation(
      parent: _rotationController,
      curve: widget.animationCurve,
    ));

    // 监听动画变化
    _rotationAnimation.addListener(() {
      widget.onRotationChanged?.call(_rotationAnimation.value);
    });

    if (widget.enableAutoRotation) {
      _rotationController.repeat();
    }
  }

  @override
  void didUpdateWidget(HelicopterRotor3D oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    if (oldWidget.rotationSpeed != widget.rotationSpeed) {
      _rotationController.duration = _calculateDuration(widget.rotationSpeed);
    }

    if (oldWidget.enableAutoRotation != widget.enableAutoRotation) {
      if (widget.enableAutoRotation) {
        _rotationController.repeat();
      } else {
        _rotationController.stop();
      }
    }
  }

  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  /// 根据旋转速度计算动画时长
  /// rotationSpeed: 每秒旋转圈数
  /// 返回：每圈的时长
  Duration _calculateDuration(double speed) {
    // 防止除零错误，最小速度为0.001（每1000秒一圈）
    final safeSpeed = math.max(speed, 0.001);
    // 每圈时长（毫秒） = 1000毫秒 / 每秒圈数
    final millisecondsPerRotation = (1000 / safeSpeed).round();
    return Duration(milliseconds: millisecondsPerRotation);
  }

  /// 创建直升机旋翼式3D变换矩阵
  /// 
  /// 变换顺序很重要：
  /// 1. 先进行空间倾斜变换（X轴和Y轴）
  /// 2. 然后围绕Z轴旋转（这是旋翼的旋转轴）
  /// 3. 最后应用透视效果
  Matrix4 _createHelicopterRotorTransform(double rotationAngle) {
    final matrix = Matrix4.identity();

    // 设置透视效果
    if (widget.enablePerspective) {
      matrix.setEntry(3, 2, -widget.perspectiveValue);
    }

    // 关键：先进行空间倾斜变换
    matrix.rotateX(widget.tiltAngleX);  // X轴倾斜
    matrix.rotateY(widget.tiltAngleY);  // Y轴倾斜
    
    // 然后围绕Z轴旋转（这是旋翼的旋转轴）
    matrix.rotateZ(rotationAngle);

    return matrix;
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.enableAutoRotation) {
      return Transform(
        alignment: Alignment.center,
        transform: widget.enablePerspective 
          ? _createHelicopterRotorTransform(0.0)
          : Matrix4.identity(),
        child: widget.child,
      );
    }

    return AnimatedBuilder(
      animation: _rotationAnimation,
      builder: (context, child) {
        return Transform(
          alignment: Alignment.center,
          transform: _createHelicopterRotorTransform(_rotationAnimation.value),
          child: widget.child,
        );
      },
    );
  }
}

/// 直升机旋翼控制器
class HelicopterRotorController {
  AnimationController? _controller;
  
  void _setController(AnimationController controller) {
    _controller = controller;
  }
  
  /// 开始旋转
  void start() {
    _controller?.repeat();
  }
  
  /// 停止旋转
  void stop() {
    _controller?.stop();
  }
  
  /// 暂停旋转
  void pause() {
    _controller?.stop();
  }
  
  /// 重置到初始状态
  void reset() {
    _controller?.reset();
  }
  
  /// 设置旋转速度（每秒圈数）
  void setSpeed(double speedPerSecond) {
    if (_controller != null) {
      final currentValue = _controller!.value;
      final safeSpeed = math.max(speedPerSecond, 0.001);
      final millisecondsPerRotation = (1000 / safeSpeed).round();
      _controller!.duration = Duration(milliseconds: millisecondsPerRotation);
      _controller!.forward(from: currentValue);
    }
  }
}

/// 高级直升机旋翼组件（支持外部控制）
class AdvancedHelicopterRotor3D extends StatefulWidget {
  final Widget child;
  final double rotationSpeed;
  final double tiltAngleX;
  final double tiltAngleY;
  final double perspectiveValue;
  final bool enableAutoRotation;
  final bool enablePerspective;
  final Curve animationCurve;
  final void Function(double angle)? onRotationChanged;
  final HelicopterRotorController? controller;

  const AdvancedHelicopterRotor3D({
    Key? key,
    required this.child,
    this.rotationSpeed = 0.5, // 默认每2秒旋转一圈
    this.tiltAngleX = 0.3,
    this.tiltAngleY = 0.0,
    this.perspectiveValue = 0.001,
    this.enableAutoRotation = true,
    this.enablePerspective = true,
    this.animationCurve = Curves.linear,
    this.onRotationChanged,
    this.controller,
  }) : super(key: key);

  @override
  State<AdvancedHelicopterRotor3D> createState() => _AdvancedHelicopterRotor3DState();
}

class _AdvancedHelicopterRotor3DState extends State<AdvancedHelicopterRotor3D>
    with TickerProviderStateMixin {
  late AnimationController _rotationController;
  late Animation<double> _rotationAnimation;

  @override
  void initState() {
    super.initState();
    
    _rotationController = AnimationController(
      duration: _calculateDuration(widget.rotationSpeed),
      vsync: this,
    );
    
    // 连接控制器
    widget.controller?._setController(_rotationController);

    _rotationAnimation = Tween<double>(
      begin: 0.0,
      end: 2 * math.pi,
    ).animate(CurvedAnimation(
      parent: _rotationController,
      curve: widget.animationCurve,
    ));

    _rotationAnimation.addListener(() {
      widget.onRotationChanged?.call(_rotationAnimation.value);
    });

    if (widget.enableAutoRotation) {
      _rotationController.repeat();
    }
  }

  @override
  void didUpdateWidget(AdvancedHelicopterRotor3D oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    if (oldWidget.rotationSpeed != widget.rotationSpeed) {
      _rotationController.duration = _calculateDuration(widget.rotationSpeed);
    }

    if (oldWidget.enableAutoRotation != widget.enableAutoRotation) {
      if (widget.enableAutoRotation) {
        _rotationController.repeat();
      } else {
        _rotationController.stop();
      }
    }
  }

  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  /// 根据旋转速度计算动画时长
  Duration _calculateDuration(double speed) {
    final safeSpeed = math.max(speed, 0.001);
    final millisecondsPerRotation = (1000 / safeSpeed).round();
    return Duration(milliseconds: millisecondsPerRotation);
  }

  /// 创建直升机旋翼式3D变换矩阵
  Matrix4 _createHelicopterRotorTransform(double rotationAngle) {
    final matrix = Matrix4.identity();

    if (widget.enablePerspective) {
      matrix.setEntry(3, 2, -widget.perspectiveValue);
    }

    matrix.rotateX(widget.tiltAngleX);
    matrix.rotateY(widget.tiltAngleY);
    matrix.rotateZ(rotationAngle);

    return matrix;
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.enableAutoRotation) {
      return Transform(
        alignment: Alignment.center,
        transform: widget.enablePerspective 
          ? _createHelicopterRotorTransform(0.0)
          : Matrix4.identity(),
        child: widget.child,
      );
    }

    return AnimatedBuilder(
      animation: _rotationAnimation,
      builder: (context, child) {
        return Transform(
          alignment: Alignment.center,
          transform: _createHelicopterRotorTransform(_rotationAnimation.value),
          child: widget.child,
        );
      },
    );
  }
}

/// 预设的旋翼样式
class RotorStyles {
  /// 超慢旋转（每100秒一圈）
  static const double ultraSlowRotation = 0.01;
  
  /// 很慢旋转（每20秒一圈） 
  static const double verySlowRotation = 0.05;
  
  /// 缓慢旋转（每10秒一圈）
  static const double slowRotation = 0.1;
  
  /// 正常旋转（每2秒一圈）
  static const double normalRotation = 0.5;
  
  /// 快速旋转（每秒一圈）
  static const double fastRotation = 1.0;
  
  /// 超快旋转（每秒2圈）
  static const double veryFastRotation = 2.0;
} 